/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lvoddownloader;

import Lvod.Config.ConfigLoader;
import java.io.File;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author wcss
 */
public class ConfigEditor extends javax.swing.JFrame {

    /**
     * Creates new form ConfigEditor
     */
    public ConfigEditor() {
        initComponents();
        //this.textSourceFile.setText(ConfigLoader.config.qvodSourceFile);
        //this.jsrSourceLength.setValue(ConfigLoader.config.qvodSourceLength);
        this.jsrTimeout.setValue(ConfigLoader.config.downloadTimeout);
        //this.textRunScript.setText(ConfigLoader.config.downloadRunScript);
        //this.textPlayScript.setText(ConfigLoader.config.playRunScript);
        this.textDownLoadDir.setText(ConfigLoader.config.downloadDir);
        //this.textPlayListName.setText(ConfigLoader.config.playListName);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel2 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        textDownLoadDir = new javax.swing.JTextField();
        btnSave = new javax.swing.JButton();
        btnClose = new javax.swing.JButton();
        jsrTimeout = new javax.swing.JSpinner();
        jLabel8 = new javax.swing.JLabel();
        btnSelectDir = new javax.swing.JButton();
        btnClearBufferDirs = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("系统配置");
        setAlwaysOnTop(true);
        setResizable(false);

        jLabel2.setText("下载超时时间：");

        jLabel6.setText("影片下载目录：");

        textDownLoadDir.setText("jTextField1");

        btnSave.setText("保存");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnClose.setText("关闭");
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });

        jLabel8.setText("秒");

        btnSelectDir.setText("选择");
        btnSelectDir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelectDirActionPerformed(evt);
            }
        });

        btnClearBufferDirs.setText("清理下载缓存");
        btnClearBufferDirs.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnClearBufferDirsActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addComponent(jLabel2)
                .addGap(12, 12, 12)
                .addComponent(jsrTimeout, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(4, 4, 4)
                .addComponent(jLabel8))
            .addGroup(layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addComponent(jLabel6)
                .addGap(12, 12, 12)
                .addComponent(textDownLoadDir, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(6, 6, 6)
                .addComponent(btnSelectDir))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(11, 11, 11)
                .addComponent(btnClearBufferDirs, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(20, 20, 20)
                .addComponent(btnClose, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jsrTimeout, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel8))))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(5, 5, 5)
                        .addComponent(jLabel6))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(textDownLoadDir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(btnSelectDir))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnSave)
                    .addComponent(btnClearBufferDirs)
                    .addComponent(btnClose))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_btnCloseActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        // TODO add your handling code here:
        if (Integer.parseInt(this.jsrTimeout.getValue().toString()) < 120)
        {
            javax.swing.JOptionPane.showMessageDialog(null, "下载超时时间不能小于120秒!");
        }else if (!new File(this.textDownLoadDir.getText().trim()).exists())
        {
            javax.swing.JOptionPane.showMessageDialog(null, "下载目录不存在!");
        }else
        {       
           ConfigLoader.config.downloadTimeout = Integer.parseInt(this.jsrTimeout.getValue().toString());
           ConfigLoader.config.downloadDir = this.textDownLoadDir.getText().trim();
            try {
                ConfigLoader.config.saveConfig(JAppToolKit.JRunHelper.getUserHomeDirPath() + "/.qvodcache.cfg");
                JAppToolKit.JRunHelper.runSysCmd("gksu mv " + JAppToolKit.JRunHelper.getUserHomeDirPath() + "/.qvodcache.cfg" + " " + ConfigLoader.systemConfigPath +"",true);
                javax.swing.JOptionPane.showMessageDialog(null, "保存完成！");
                this.dispose();
            } catch (Exception ex) {
                Logger.getLogger(ConfigEditor.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
    }//GEN-LAST:event_btnSaveActionPerformed

    private void btnSelectDirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelectDirActionPerformed
        // TODO add your handling code here:
        javax.swing.JFileChooser jfc = new javax.swing.JFileChooser();
        jfc.setMultiSelectionEnabled(false);
        jfc.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);
        jfc.setDialogTitle("选择下载目录！");
        int dialog = jfc.showOpenDialog(null);
        if (dialog == javax.swing.JFileChooser.APPROVE_OPTION)
        {
            this.textDownLoadDir.setText(jfc.getSelectedFile().getAbsolutePath());
        }
        
    }//GEN-LAST:event_btnSelectDirActionPerformed

    private void btnClearBufferDirsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearBufferDirsActionPerformed
        // TODO add your handling code here:
        File ff = new File(ConfigLoader.config.downloadDir + "/.qvodcache");
        ArrayList<String> nowData = new ArrayList<String>();        
        if (LDownLoadList.data != null)
        {
            ArrayList<LDownLoadItem> al = new ArrayList<LDownLoadItem>(LDownLoadList.data.downloadItemMap.values());
            for(int k = 0;k < al.size();k++)
            {
                 nowData.add(al.get(k).downloaderObj.qvodWorkDir);
            }
        }        
        if (ff.exists())
        {
            File[] team = ff.listFiles();
            for(File f: team)
            {
                if (f.isDirectory())
                {
                    if (!nowData.contains(f.getAbsolutePath()))
                    {
                        try {
                            JAppToolKit.JRunHelper.runSysCmd("rm -rf " + f.getAbsolutePath());
                        } catch (Exception ex) {
                            Logger.getLogger(ConfigEditor.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }
        }
        javax.swing.JOptionPane.showMessageDialog(null, "缓存清理完成！");
        this.dispose();
    }//GEN-LAST:event_btnClearBufferDirsActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void hidemain(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ConfigEditor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ConfigEditor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ConfigEditor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ConfigEditor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ConfigEditor().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClearBufferDirs;
    private javax.swing.JButton btnClose;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnSelectDir;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JSpinner jsrTimeout;
    private javax.swing.JTextField textDownLoadDir;
    // End of variables declaration//GEN-END:variables
}
